package com.homedo.microservice.wechat.personal.secretary.remote.api.impl;

import com.homedo.microservice.wechat.personal.secretary.api.IBotQrCodeRemote;
import com.homedo.microservice.wechat.personal.secretary.entity.PersonalBot;
import com.homedo.microservice.wechat.personal.secretary.service.PersonalBotService;
import io.github.biezhi.wechat.exception.WeChatException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

@Controller
public class BotQrCodeRemoteImpl implements IBotQrCodeRemote {
    private static final Logger _LOGGER = LoggerFactory.getLogger(BotQrCodeRemoteImpl.class);

    @Autowired
    private HttpServletResponse httpServletResponse;

    @Autowired
    private PersonalBotService personalBotService;

    @Override
    public void getQrCode(String account) throws IOException {
        PersonalBot personalBot = personalBotService.getPersonalBot(account, null);
        personalBot.api().getLoginQrImage();


        String downloadPath = personalBot.config().assetsDir() + "/" + personalBot.config().filePrefix() + "qrcode.png";

        File downFile = new File(downloadPath);
        long downFileLength = downFile.length();

        httpServletResponse.addHeader("Content-Length", String.valueOf(downFileLength));
        httpServletResponse.addHeader("Accept-Ranges", "bytes");
        httpServletResponse.addHeader("Content-Range", "bytes 0-" + (downFileLength - 1) + "/" + downFileLength);

        _LOGGER.info("[开始下载文件:{}--{}--{}]", downloadPath, downFileLength);
        OutputStream out = httpServletResponse.getOutputStream();
        writeFileToResponse(httpServletResponse, downFile, out);
    }

    protected void writeFileToResponse(HttpServletResponse response, File downFile, OutputStream out) {
        // 写文件到response
        FileInputStream in = null;
        try {
            if (downFile == null || !downFile.exists()) {
                throw new WeChatException("文件不存在");
            }
            response.setCharacterEncoding("utf-8");
            response.setContentType("octets/stream");
            // response.addHeader("Content-Type", "text/html; charset=utf-8");
            response.addHeader("Content-Type", "multipart/form-data");
            response.addHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
//            response.addHeader("voiceFileSize", String.valueOf(downFile.length()));// 添加文件大小
            String downLoadName = new String(downFile.getName().getBytes("gbk"), "iso8859-1");
            response.setHeader("Content-Disposition", "attachment;fileName=" + downLoadName);
            in = new FileInputStream(downFile);
            int len = 0;
            byte buffer[] = new byte[1024];
            while ((len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }

        } catch (Exception e) {
            throw new WeChatException("文件下载出错:" + e.getMessage());
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
